<template>
    <div class="app-container">
        <div v-if="songs.length > 0" class="songList">
            <div class="recommendation-container">
                <h3 class="left-bar-50">根据您常听的标签{{ currentTag ? currentTag.tagName : '未知标签' }}，为您推荐</h3>
                <h5 @click="refreshSongs" class="refresh-text">换一换</h5>
                <h5 @click="refreshTags" class="refresh-text">换标签（查询时间略长，请稍等）</h5>
            </div>
            <div v-if="loading">加载中...</div>
            <el-table :data="randomSelectedSongs" >
                <el-table-column label="序号" width="100" align="center">
                    <template #default="scope">
                        <span>{{ scope.$index + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="trackId" label="歌曲ID" width="150"></el-table-column>
                <el-table-column prop="title" label="歌曲名"></el-table-column>
                <el-table-column prop="artistName" label="歌手"></el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import { getUserTopTags, getTagRecommend } from '@/api/UserTopTags/UserTopTags.js';
import useUserStore from '@/store/modules/user';

const userStore = useUserStore();
const currentUserId = computed(() => userStore.id);

export default {
    name: 'TopSongsByTag',
    data() {
        return {
            tagsData: [],
            songs: [],
            randomSelectedSongs: [],
            currentTag: []
        };
    },
    created() {
        this.fetchTagsData();
    },
    methods: {
        async fetchTagsData() {
            try {
                const response = await getUserTopTags(currentUserId.value);
                this.tagsData = response.data;
                this.selectRandomTag();
            } catch (error) {
                console.error('Error fetching tags data:', error);
            }
        },
        selectRandomTag() {
            if (this.tagsData.length > 0) {
                const randomIndex = Math.floor(Math.random() * this.tagsData.length);
                const randomTag = this.tagsData[randomIndex];
                this.currentTag = this.tagsData[randomIndex];
                this.getTagRecommend(randomTag.tagId);
            }
        },
        async getTagRecommend(tagId) {
            try {
                const response = await getTagRecommend(tagId);
                console.info(response)
                this.songs = response.data.map(item => ({
                    title: decodeURIComponent(item.title.replace(/\+/g, ' ').replace("_", "——")),
                    trackId: item.id,
                    artistName: decodeURIComponent(item.artistName.replace(/\+/g, ' ').replace("_", "——")),
                }));
                this.selectRandomSongs();
            } catch (error) {
                console.error('Error fetching songs data:', error);
            }
        },
        selectRandomSongs() {
            if (this.songs.length > 0) {
                const randomIndices = [];
                while (randomIndices.length < 5) {
                    const randomIndex = Math.floor(Math.random() * this.songs.length);
                    if (!randomIndices.includes(randomIndex)) {
                        randomIndices.push(randomIndex);
                    }
                }
                this.randomSelectedSongs = randomIndices.map(index => this.songs[index]);
            }
        },
        refreshSongs() {
            this.randomSelectedSongs = [];
            this.selectRandomSongs();
        },
        refreshTags() {
            songs: [];
            randomSelectedSongs: [];
            currentTag: [];
            this.selectRandomTag();
        }
    }
};
</script>

<style scoped>
.songList {
    margin: 30px auto;
    font-size: 20px;
    font-family: '微软雅黑';
}
ul {
    list-style-type: none;
    padding: 0;
}
li {
    margin: 10px 0;
}
button {
    margin-top: 20px;
    font-size: 16px;
    padding: 10px 20px;
    cursor: pointer;
}
.recommendation-container {
    display: flex;
    align-items: center; /* 垂直居中对齐 */
    justify-content: space-between; /* 两端对齐 */
    margin: 30px auto;
    font-size: 20px;
    font-family: '微软雅黑';
    font-weight: bold;
}

.refresh-text {
    float: left;
    cursor: pointer;
    padding: 10px;
    font-size: 16px;
    color: #007bff;
}

.refresh-text:hover {
    text-decoration: none;
    text-decoration: underline;
    color: #0056b3;
}
.app-container {
    padding: 20px;
}
</style>